package com.cgtong.android.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.LogUtils;
import com.cgtong.android.R;
import com.cgtong.android.activity.LocalImagePreviewActivity;
import com.cgtong.android.bean.ProblemBean;
import com.cgtong.android.widget.GlideApp;

import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;


public class ImagePreviewAdapter extends PagerAdapter implements PhotoViewAttacher.OnPhotoTapListener {

    private List<ProblemBean.ResourceBean> urls;
    private Context context;

    public ImagePreviewAdapter(Context context, @NonNull List<ProblemBean.ResourceBean> urls) {
        super();
        this.urls = urls;
        this.context = context;
    }

    @Override
    public int getCount() {
        return urls.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_photoview, container, false);
//        final ProgressBar pb = (ProgressBar) view.findViewById(R.id.pb);
        final PhotoView imageView = (PhotoView) view.findViewById(R.id.pv);

        String info = this.urls.get(position).getContent();
        LogUtils.d("info: "+info);
        imageView.setOnPhotoTapListener(this);
        GlideApp.with(context).load(info)
                .dontAnimate()
                .placeholder(R.drawable.icon_default_loading)
                .error(R.drawable.icon_default_error).into(imageView);
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    /**
     * 单击屏幕关闭
     */
    @Override
    public void onPhotoTap(View view, float x, float y) {
        ((LocalImagePreviewActivity) context).finish();
    }
}